package quq.missq.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.photoselector.model.PhotoModel;
import com.photoselector.ui.PhotoSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import quq.missq.BaseActivity;
import quq.missq.Constants;
import quq.missq.MLog;
import quq.missq.R;
import quq.missq.adapter.PublishTopicImageAdapter;
import quq.missq.beans.Author;
import quq.missq.utils.HttpRequest;
import quq.missq.utils.ImageUploadAsyncTask;
import quq.missq.utils.UserTools;
import quq.missq.utils.VolleyTool;
import quq.missq.views.NoScrollGridView;

/**
 * Created by River on 8/10/15.
 */
public class PublishTopicActivity extends BaseActivity implements View.OnClickListener{

    private TextView mTopicType;
    private ImageView mTopicIcon;
    private TextView mCancel;
    private TextView mSend;
    private EditText mContent;
    private ImageView mAtPeople;
    private ImageView mChoosePic;
    private TextView mHideName;
    private ImageView mHideIcon;
    private TextView mAtContent;
    private String atContent = "";
    private ProgressDialog dialog;

    private NoScrollGridView mGridView;
    private PublishTopicImageAdapter mAdapter;
    private ArrayList mPhotoes;

    private int anon = 0;// 0 不匿名，1 匿名
    private int categoryId = 0; // 5 QA 4 秀喷
    private String atUserIds = "";
    private String mUserName;
    private TextView tv_publish;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.publish_topic_activity);
        categoryId = getIntent().getIntExtra("category", 0);
        atUserIds = getIntent().getStringExtra("userId");
        mUserName = getIntent().getStringExtra("userName");
        initView();
        initListener();
        initData();
    }

    private void initView(){

        mTopicType = (TextView)findViewById(R.id.topicType);
        mTopicIcon = (ImageView)findViewById(R.id.topicIcon);
        mCancel = (TextView)findViewById(R.id.cancel);
        mSend = (TextView)findViewById(R.id.send);
        mContent = (EditText)findViewById(R.id.content);
        mAtPeople = (ImageView)findViewById(R.id.atPeople);
        mChoosePic = (ImageView)findViewById(R.id.choosePic);
        mHideName = (TextView)findViewById(R.id.hideName);
        mHideIcon = (ImageView)findViewById(R.id.hideIcon);
        mGridView = (NoScrollGridView)findViewById(R.id.gridview);
        mAtContent = (TextView)findViewById(R.id.atContent);
        tv_publish = (TextView) findViewById(R.id.tv_publish);
       // mTopicIcon.setImageResource(R.mipmap.arrow_up);
        if(categoryId == 5){
            mTopicType.setText("Q&A");
//            tv_publish.setText("有什么问题？可以直接向女神提出来哦~~");
            tv_publish.setText("如果你的问题精彩，女神会公开回答哦~ ~");
        }else if(categoryId == 4){
            mTopicType.setText("秀&喷");
            tv_publish.setText("有什么心情，快发出来吧~");
        }
        if(mUserName != null){
            atContent = atContent+"@"+mUserName;
            mAtContent.setText(atContent);
        }

    }

    private void initListener(){
        mTopicType.setOnClickListener(this);
        mCancel.setOnClickListener(this);
        mSend.setOnClickListener(this);
        mAtPeople.setOnClickListener(this);
        mChoosePic.setOnClickListener(this);
        mHideName.setOnClickListener(this);
    }

    private void initData(){
        mAdapter = new PublishTopicImageAdapter(this);
        mPhotoes = new ArrayList();
        mAdapter.setData(mPhotoes);
        mGridView.setAdapter(mAdapter);
    }

    private static final int CHOOSE_PIC = 0;
    private static final int CHOOSE_PEOPLE = 1;

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            /*case R.id.topicType:
                onTopicType();
                break;*/
            case R.id.cancel:
                this.finish();
                break;
            case R.id.send:
                send();
                break;
            case R.id.atPeople:
                if(categoryId == 5){
                    intent = new Intent(this, AtNvShenListActivity.class);
                    startActivityForResult(intent, CHOOSE_PEOPLE);
                }else if(categoryId == 4){
                    intent = new Intent(this, MyContractorActivity.class);
                    startActivityForResult(intent, CHOOSE_PEOPLE);
                }
                break;
            case R.id.choosePic:
                intent = new Intent(this, PhotoSelectorActivity.class);
                intent.putExtra(PhotoSelectorActivity.KEY_MAX, 9-mPhotoes.size());
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivityForResult(intent, CHOOSE_PIC);
                break;
            case R.id.hideName:
                if(mHideIcon.getVisibility() == View.GONE){
                    mHideIcon.setVisibility(View.VISIBLE);
                    anon = 1;
                }else{
                    mHideIcon.setVisibility(View.GONE);
                    anon = 0;
                }
                break;
            /*case R.id.qa:
                categoryId = 5;
                if(mDialog != null){mDialog.dismiss();}
                mTopicType.setText("Q&A");
                break;
            case R.id.show:
                categoryId = 4;
                mTopicType.setText("秀喷");
                if(mDialog != null){mDialog.dismiss();}
                break;*/
        }
    }

    private void send(){
        String content = mContent.getText().toString();
        if(TextUtils.isEmpty(content)){
            showToast("话题不能为空");
            return;
        }
        if(mHideIcon.getVisibility() == View.VISIBLE){
            anon = 1;
        }else{
            anon = 0;
        }
        if(categoryId == 0){
            showToast("请选择话题类型");
            return;
        }
        String acc_token = UserTools.getUser(this).getAcc_token();
        Map<String,String> params = new HashMap<>();
        params.put("categoryId",categoryId+"");
        params.put("content",content);
        params.put("atUserIds",atUserIds);
        params.put("acc_token",acc_token);
        params.put("anon",anon+"");
        dialog = ProgressDialog.show(this, "提示", "提交中...", false, false);

        Map<String,File> files = new HashMap<>();
        ArrayList<PhotoModel> photoes = mAdapter.getPhotoes();
        File file;
        for (int i=0;i<photoes.size();i++){
            file = new File(photoes.get(i).getOriginalPath());
            files.put("pic"+i,file);
        }

        ImageUploadAsyncTask imageUploadAsyncTask = new ImageUploadAsyncTask(params,files, Constants.PUBLISH_TOPIC_URL,new HttpRequest.HttpRequestListener() {
            @Override
            public void httpError() {
                if(dialog!=null){dialog.dismiss();}
                showToast("发布失败，请重试");
            }

            @Override
            public void httpSuccess(String msg) {
                MLog.e(msg);

                if(dialog!=null){dialog.dismiss();}
                try {
                    JSONObject obj = new JSONObject(msg);
                    int code = obj.getInt("code");
                    String message = obj.getString("message");
                    if(code >= 0){
                        Intent intent = new Intent();
                        intent.putExtra("msg",msg);
                        setResult(RESULT_OK,intent);
                        PublishTopicActivity.this.finish();
                    }else{
                        showToast(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },"files");
        imageUploadAsyncTask.execute();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == CHOOSE_PIC) {
            ArrayList<PhotoModel> photos = (ArrayList<PhotoModel>) data.getSerializableExtra("photos");
            if (photos != null) {
                for (int i = 0;i < photos.size();i++){
                    mAdapter.addData(photos.get(i));
                }
            }
            mAdapter.notifyDataSetChanged();
        }else if(resultCode == RESULT_OK && requestCode == CHOOSE_PEOPLE){
            Author author = (Author)data.getSerializableExtra("author");
            if("".equals(atContent)){
                atUserIds = author.getId()+"";
                atContent = "@"+author.getNkname();
            }else{
                atUserIds = atUserIds+","+author.getId();
                atContent = atContent+",@"+author.getNkname();
            }
            mAtContent.setText(atContent);
        }
    }
    private void onTopicType(){
        showDialog();
//        if(isUp){
//            mTopicIcon.setImageResource(R.mipmap.arrow_down);
//            isUp = false;
//            showDialog();
//        }else{
//            mTopicIcon.setImageResource(R.mipmap.arrow_up);
//            isUp = true;
//        }
    }

    private AlertDialog mDialog;
    public void showDialog() {
        View v = LayoutInflater.from(this).inflate(R.layout.choose_topic_type, null);
        ImageView qa = (ImageView)v.findViewById(R.id.qa);
        ImageView show = (ImageView)v.findViewById(R.id.show);
        qa.setOnClickListener(this);
        show.setOnClickListener(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        mDialog = builder.setView(v).create();
        mDialog.show();
    }

//    @Override         ,VolleyTool.HTTPListener
//    public <T> void onResponse(T t, int requestCode) {
//
//    }
//
//    @Override
//    public void onErrorResponse(VolleyError error, int requestCode) {
//
//    }

}
